package org.osomit.sacct.security.otp.impl;

import org.osomit.sacct.security.otp.impl.FileOTPTokenReaderWriter;
import org.osomit.sacct.security.otp.impl.HOTPAlgorithm;
import org.osomit.sacct.security.otp.impl.OTPTokenImpl;
import org.osomit.sacct.security.otp.iface.OTPToken;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import static junit.framework.Assert.fail;

/**
 * Test to read token from file and write to file
 *
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jun 26, 2009
 */
public class FileOTPTokenReaderWriter_UT {
	private static String SECRET_STRING = "12345678901234567890";
	private static long initCount = 100;
	private static int codeDigits = 9;
	private static boolean addChecksum = true;
	private static int truncationOffset = 20;
	private static String SN = "321151351351";
	private static String password = "good4you";
	private static int stepSize = 100;
	private static FileOTPTokenReaderWriter readerWriter;
	private static String FILE_NAME = "HOTP.TOKEN";
	private static HOTPAlgorithm algorithm;

	@BeforeClass
	public static void singleSetup() throws Exception{
		readerWriter = new FileOTPTokenReaderWriter();
		readerWriter.setFileName(FILE_NAME);
		readerWriter.setPassword(password);
		algorithm = new HOTPAlgorithm();
	}

	@AfterClass
	public static void singleTearDown() {
		algorithm = null;
		readerWriter = null;
	}

	@Test
	public void testWriteToken(){
		OTPToken token = new OTPTokenImpl(SN, SECRET_STRING.getBytes(), initCount, codeDigits,
				addChecksum, truncationOffset, stepSize, algorithm);
		try {
			readerWriter.write(token);
		} catch (Exception e) {
			fail(e.getLocalizedMessage());
		}

	}

	@Test
	public void testReadToken(){
		OTPToken token = new OTPTokenImpl(SN, SECRET_STRING.getBytes(), initCount, codeDigits,
				addChecksum, truncationOffset, stepSize, algorithm);
		try {
			readerWriter.write(token);
		} catch (Exception e) {
			fail(e.getLocalizedMessage());
		}

		try {
			token = readerWriter.read();
			assertNotNull(token);
			assertEquals(SN, token.getSN());

			for (int i = 0; i < 10; i++) {
				String otp = token.generateOTP();
				System.out.println("Count " + (initCount + i) + " OTP " + otp);
			}
		} catch (Exception e) {
			fail(e.getLocalizedMessage());
		}
	}
}
